// pages/auth/auth.js
const { getSmsCode, verifySmsCode, getLogin } = require('../../api/index.js')

Page({
  data: {
    phoneNumber: '',
    smsCode: '',
    countdown: 0,
  },

  // 输入手机号
  onPhoneInput(e) {
    this.setData({ phoneNumber: e.detail.value })
  },

  // 输入验证码
  onSmsCodeInput(e) {
    this.setData({ smsCode: e.detail.value })
  },

  // 获取验证码
  async getSmsCode() {
    const { phoneNumber } = this.data
    if (!/^1\d{10}$/.test(phoneNumber)) {
      wx.showToast({ title: '请输入正确的手机号', icon: 'none' })
      return
    }

    try {
      await getSmsCode( phoneNumber )
      wx.showToast({ title: '验证码已发送', icon: 'success' })

      let count = 60
      this.setData({ countdown: count })
      const timer = setInterval(() => {
        count--
        if (count <= 0) {
          clearInterval(timer)
          this.setData({ countdown: 0 })
        } else {
          this.setData({ countdown: count })
        }
      }, 1000)
    } catch (err) {
      wx.showToast({ title: '发送失败', icon: 'none' })
    }
  },

  // 提交：由后端判断是否注册，自动登录或注册
  async handleSubmit() {
    const { phoneNumber, smsCode } = this.data

    if (!phoneNumber || !smsCode) {
      wx.showToast({ title: '请填写手机号和验证码', icon: 'none' })
      return
    }
  
    try {
      // 调用后端接口，后端自动判断注册/登录
      const res = await getLogin({ phone: phoneNumber, code: smsCode })
      const userInfo = {
        phone: phoneNumber
      }
  
      // 保存用户信息、token和refreshToken
      wx.setStorageSync('userInfo', userInfo)
      wx.setStorageSync('token', res.data.token)
      // 保存refreshToken
      if (res.data.refreshtoken) {
        wx.setStorageSync('refreshToken', res.data.refreshtoken)
      }
        
      wx.showToast({ title: '登录成功', icon: 'success' })
  
      // 跳转到首页
      wx.switchTab({ url: '/pages/index/index' })
    } catch (err) {
      wx.showToast({ title: '登录/注册失败', icon: 'none' })
    }
  }
})
